$().ready(function(){
    bindLoginUI();    
    bindActionBoxUI();
    calculateOffset();
    singlePageComment();
    bindAvatarUpload();
    bindCreatePhoto();
    bindModeratorActions();
    initialiseJGrowl();
	if ($('section.cab').length) {
      JayzKeaneLinkinPark();
    }
    if($.browser.mozilla || $.browser.webkit){
     if($('#maincontent #cablist').length != 0) bindFloatingVoteBox();   
    }
    bindTwitter();
    linktifyComments();
    bindJsActionFollow();
    
    function linktifyComments(){
        $('.entry-content .entry-text').livequery(function(){
            var t = $(this).find('.textwrap').html();
            $(this).find('.textwrap').html(linkify(t))
        });
    }
        
    function isLoggedIn(){
        if($.cookie('TheCabProject') != null){            
            return true;
        }else return false;       
    }
    
    function linkify(text){
        if (text) {
            text = text.replace(
                /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
                function(url){
                    var full_url = url;
                    if (!full_url.match('^https?:\/\/')) {
                        full_url = 'http://' + full_url;
                    }
                    return '<a href="' + full_url + '">' + url + '</a>';
                }
            );
        }
        return text;
    }
    /**
     *  UI dành cho login box
     *
     *
     */
    function bindLoginUI(){
        var parent = $('#signin');
        $('.login',parent).click(function(){            
            $(this).toggleClass('active');
            $('#loginbox',parent).stop(true,true).slideToggle('fast');
            return false;
        });
        $('.userinfo',parent).click(function(){
            $('.notificationwrap.active', parent).toggleClass('active');
            $(parent).find('#notificationspop.visible-popup').removeClass('visible-popup').hide();
            $(this).toggleClass('active');            
            $('#userexpandbox',parent).toggleClass('visible-popup').stop(true,true).slideToggle('fast');
            return false;
        });
        
        $('.notificationwrap', parent).click(function(){
            $('.userinfo.active',parent).toggleClass('active');
            $(parent).find('#userexpandbox.visible-popup').removeClass('visible-popup').hide();
            $(this).toggleClass('active');            
            $('#notificationspop',parent).toggleClass('visible-popup').stop(true,true).toggle();
            return false;
        });
    }    
    
    
    /**
     * UI dành cho box quick vote/ quick comment bên tay phải
     * 
     */
    function bindActionBoxUI(){       
        if(!isLoggedIn()) return;
        
        var voteUpURL = 'post/voteUp/';
        var voteDownURL = 'post/voteDown/';
        
        $('#cablist .cab').each(function(){
            var parent = $(this);
            var post_id = $(parent).find('input[name=cabid]').val();
            
            
            //toggle comment box
            $('.commentbox', parent).click(function(){
                var handler  = $(this);                               
                $(this).toggleClass('active');
                $('.comment-expand', parent).stop(true,true).toggle(); 
            });
            
            //bind submit action to quickcomment form                        
            $('.comment-expand textarea',parent).keypress(function(event){
                if(event.which != 13) return true;
                if(event.which == 13 && $(this).val().length ==0){
                    $('.comment-expand', parent).stop(true,true).toggle();          
                    return false;
                }
                if(event.which == 13 && event.shiftKey == false){
                    var textarea = $(this);
                    var comment = $(this).val().replace(/(<([^>]+)>)/ig,"");                        
                    var url = $('form', parent).attr('action');            
                    var postID = $(this).closest('form').find('input[name=postID]').val();                    
                    $.post(url, {'comment': comment, 'postID': postID}, function(data){                            
                        if(data.success == false){
                            $.jGrowl(data.message, { header: 'Chú ý'});
                            return false;
                        }
                        $('.commentcount .count',parent).text(data.comment);
                    },'json').success(function(){                        
                        textarea.val('');
                        $('.comment-expand', parent).stop(true,true).toggle();
                    });
                    return false;
                }
                return false;
            });
            
            
            //submit quick vote hình trái tim
            $('.heart',parent).click(function(){
                var handler = $(this);
                if(handler.data('running')) return;
                else handler.data('running',true);
                
                //toggle display
                
                var url = voteUpURL + post_id;
                if($(this).hasClass('active')) url = voteDownURL + post_id;      
                
                $(this).toggleClass('active');
                $.post(url, function(data){                      
                        //$('body').data('data',data);
                        $('.votecounter .counter',parent).text(data.vote);
                        $('.commentcount .count',parent).text(data.comment);
                        handler.data('running',false);
                    },'json');
            });
        });
    }
    
    //Bind action cho toàn bộ page single
    function singlePageComment(){
        var parent = $('#maincontent .singlecabmain');
        
        
        $().data('commentblock',$('.replycomment', parent));
        //Update remaining character count.
        $('.replycomment textarea', parent).keyup(function(event){                  
            var l = $(this).attr('maxlength') - $(this).val().length;
            $(this).closest('.replycomment').find('.desc > span').text(l);                       
        });
        
        //Bind handler to main comment block
        $(parent).data('comment_entry_blank', $('#comment_entry_blank').remove());
        $(parent).data('reply-comment-inline-block', $('#reply-comment-inline-block').remove());
        
        var cbocx = $('#commentboxmain');
        $('#commentboxmain').ajaxForm({
            dataType: 'json',
            beforeSubmit: function(formData, jqForm, options){
                if($(cbocx).data('sending') == true){                    
                    return false;
                }else{
                    $(cbocx).data('sending',true);
                }
                if($('textarea', jqForm).val().length == 0) return false;
                $(this).data('form', jqForm);
                $(jqForm).find('input[type=submit]').val('Đang gửi...').end()
                         .block({message: null , overlayCSS: {'backgroundColor':'#eeeeee'}});
            }, 
            success: function(data){
                $(cbocx).data('sending',false);
                if(data.success == false){
                    $.jGrowl(data.message, { header: 'Chú ý'});
                    $(this).data('form').find('input[type=submit]').val('Gửi').end()                                    
                                    .unblock();
                    return;
                }                
                var comment_block = $(parent).data('comment_entry_blank').clone();
                $(comment_block).find('.textwrap').html(nl2br(data.message)).end()
                                .find('.entry-details .datetime').text(data.nicetime).end()
                                .attr('id', 'comment_' + data.id)
                                .appendTo($('.communitycomment .wrap', parent));     
                $(this).data('form').find('input[type=submit]').val('Gửi').end()
                                    .find('textarea').val('').end()
                                    .unblock();
            }
        });
        
        //Auto increase input of inline comment
        $('.communitycomment .sub-entries .reply-content textarea', parent).elastic();
        
        // Bind action to #reply inline
        $('.entry-details a.icomment_trigger',parent).livequery('click',function(){           
            var targetPerson = $(this).closest('.entry-content').find('a.author').text();            
            var replyTo = $(this).closest('.parent-entry').attr('id').substr(8);
            $('#reply-comment-inline-block').remove();
            $(this).closest('.parent-entry')
                .find('.sub-entries:not(:has(.reply-content))')
                .append(
                    $(parent).data('reply-comment-inline-block').clone()
                    .css('display','block').find('textarea').text('@'+targetPerson + ' ').end()
                    .find('input[name=replyto]').val(replyTo).end()
                );
            $('#reply-comment-inline-block textarea').focusEnd();        
            return false;
        });
        
        //Bind action to report_comment_trigger        
        
        $('.entry-details a.report',parent).livequery(function(){
            $(this).fancybox({href : '#reportcomment', onClosed: function(){
                    $('#reportcomment').find('.thanks').hide().end()
                        .find('form').show();
            }});
        });
        $('.entry-details a.report',parent).livequery('click',function(){
            var postid = $(this).closest('[id^=comment_]').attr('id').replace('comment_','');
            $('#reportcomment input[name=postid]').val(postid);
            //$('#reportcomment').show();
            
            return false;
        }); 
        
        $('#reportcomment form').ajaxForm({
            dataType: 'json',
            beforeSubmit: function(formData, jqForm, options){
                //$(jqForm).block({message: null , overlayCSS: {'backgroundColor':'#eeeeee'}});
            }, 
            success: function(data){
                $('#reportcomment form').hide().parent().find('.thanks').show();
            }
        });
        $('#blockbanuser form').ajaxForm({
            dataType: 'json',
            beforeSubmit: function(formData, jqForm, options){
                //$(jqForm).block({message: null , overlayCSS: {'backgroundColor':'#eeeeee'}});
            }, 
            success: function(data){
                $('#blockbanuser form').hide().parent().find('.thanks').show();
            }
        });
        
        // Bind action to remove_comment và hide_comment
        $('.entry-details .deletecomment_trigger',parent).livequery('click',function(){
            if(!confirm('Bạn có chắc muốn xóa comment?')) return false;
            var directparent = $(this).closest('[id^=comment_]');
            var commentID = $(this).closest('[id^=comment_]').attr('id').substr(8);
            $.post('post/deleteComment', {cid : commentID}, function(data) {
                    if(data.result){
                        $(directparent).fadeOut();
                    }
             }, 'json');            
            return false;
        });
        $('.entry-details .hidecomment_trigger',parent).livequery('click',function(){       
            var directparent = $(this).closest('[id^=comment_]');
            var commentID = $(this).closest('[id^=comment_]').attr('id').substr(8);
            $.post('post/hideComment', {cid : commentID}, function(data) {
                    if(data.result){
                        $(directparent).find('.textwrap').html($('<em/>').addClass('hide').text(data.message));
                    }
             }, 'json');            
            return false;
        });
        
        
        //post comment từ subentry, load json và hiển thị sub comment
        $(parent).data('subcomment_entry_blank',$('#subcomment_entry_blank').remove());
        $('#reply-comment-inline-block').livequery(function(){
            var wrap = $(this).closest('.parent-entry').find('.sub-entries');
            var f = $('form',this);
            $('form',this).ajaxForm({
                dataType: 'json',
                beforeSubmit: function(formData, jqForm, options){
                    if($(f).data('sending') == true){                       
                        //console.log('aborted!');
                        return false;
                    }else{
                        $(f).data('sending',true);
                    }
                    if($('textarea', jqForm).val().length == 0) return false;
                        $(this).data('form', jqForm);
                        $(jqForm).find('input[type=submit]').val('Đang gửi...').end()
                                .block({message: null , overlayCSS: {'backgroundColor':'#eeeeee'}});
                },
                success: function(data){                    
                    //gắn dữ liệu vào ô trống comment
                    $(f).data('sending',false);
                    var newblock = $(parent).data('subcomment_entry_blank').clone()
                                    .find('.textwrap').html(nl2br(data.message)).end()
                                    .find('.datetime').text(data.nicetime).end()
                                    .attr('id','comment_' + data.id)
                                    .appendTo(wrap);
                    //unblock UI
                    $(this).data('form').find('input[type=submit]').val('Gửi').end()                                    
                                    .unblock();
                    $('#reply-comment-inline-block').remove();                
                }
            });
        });
        
        //bind action cho ô trái tim bên phải
        var cabheading = $('#maincontent .cabheading');
        $('.quickvote a',cabheading).click(function(){            
            var voteUpURL = 'post/voteUp/';
            var voteDownURL = 'post/voteDown/';
            var handler = $(this);
            if(handler.data('running')) return false;
            else handler.data('running',true);

            //toggle display
            var post_id = $('#commentboxmain input[name=postID]').val();
            var url = voteUpURL + post_id;
            if($(this).hasClass('active')) url = voteDownURL + post_id;      

            $(this).toggleClass('active');
            $.post(url, function(data){                      
                    //$('body').data('data',data);
                    $('.votecount',cabheading).text(data.vote);
                    $('.commentcount',cabheading).text(data.comment);
                    handler.data('running',false);
                },'json');
            return false;
        });
    }
    
    
    function bindAvatarUpload(){
        //generate input[file] upload element        
        var maxFileSize = 5*1024 * 1024; //1MB
        var rFilter = /^(image\/bmp|image\/jpeg|image\/png)$/i;
                
        var avatarInput = $('<input/>')
                .attr('type','file')
                .attr('id','avatarupload').attr('name', 'imgavatar')
                .css('visibility','hidden')
                .appendTo('#ghostarea');
                
        $('#uploadAvavarHandler').click(function(){            
            $(avatarInput).click();
            return false;
        });
        
        
        
        $(avatarInput).bind('change',function(e){            
            var ajaxicon  = $('.settingspane .ajaxwaiting');            
            
            var file = $(avatarInput).get(0).files[0];
            var fileSize = 0;
            var fd = new FormData();
            fd.append($(avatarInput).attr('name'),file);
            $('#uploadmessage').text("");
                        
            //check file size
            if(file && file.size > maxFileSize) 
            {
                $('#uploadmessage').text("File không được lớn hơn 1MB").show();
                return false;
            }
            
            //check file type, valid types are png/bmp/jpeg
            if(file && !rFilter.test(file.type)) 
            {
                $('#uploadmessage').text("File hình không hợp lệ! Hãy chọn png, jpg, bmp").show();
                return false;
            }
            
            //okie donkey! everything looks okie ;)
            var xhr = new XMLHttpRequest();
            
            
            xhr.overrideMimeType("application/json");              
            //handle upload complete
            xhr.addEventListener("load", function(evt){
                var data = $.parseJSON(evt.target.response);
                if(data.sucess == true){
                    $('.profilehead .mainavatar, .tblsetting .avatar').attr('src', data.path);                    
                }else{
                    $('#uploadmessage').text("Hmm có lỗi gì đó xảy ra. Cá đang định hack cab à :(").show();
                }
                $(ajaxicon).hide();
            }, false);            
            
            /*
            xhr.upload.addEventListener("progress", uploadProgress, false);
            xhr.addEventListener("load", uploadComplete, false);
            xhr.addEventListener("error", uploadFailed, false);
            xhr.addEventListener("abort", uploadCanceled, false);
            xhr.open("POST", "UploadMinimal.aspx");
            */
            
            xhr.open('POST', 'settings/uploadAvatar', false);
            $('#uploadmessage').hide();
            $(ajaxicon).show(function(){
                xhr.send(fd);
            });
            
            
        });
    }
    /**
     * Bind js action and validation to /submit/phot
     *
     */
        function bindCreatePhoto(){
            var maxFileSize = 4 *1024 * 1024; //1MB
            var submitForm = $('#frmCreatePhoto');
            $(submitForm).validate({
                rules: {
                    photo: {required : true},
                    title: {required : true}
                },
                messages: {
                    photo: "Chọn hình đi cá",
                    title: "Nhập tiêu đề đi cá"
                }                

            });
            $(submitForm).bind('submit',function(){                
                
                if($('input[name=token]','#frmCreatePhoto').size() == 1){
                    return true;
                }
                var getTokenURL = 'post/validateRecaptcha';
                challengeField = $("input#recaptcha_challenge_field").val();
                responseField = $("input#recaptcha_response_field").val();
                $.post(getTokenURL, {'recaptcha_response_field': responseField, 'recaptcha_challenge_field':challengeField}, function(data){                      
                    if(!data.success){
                        $('#captchawarning').text('Có vẻ như mã bảo vệ không đúng, cá bơ thử lại nhé :)');
                        Recaptcha.reload();
                        return false;
                    }else {
                        $('#captchawarning').text('');
                        $(submitForm).append($('<input type="hidden" name="token" />').val(data.token));
                        $(submitForm).trigger('submit');
                    }
                },'json');
                return false;
            })
        }
        
    /*****************action for mod EDIT/DELTE/BAN******************/    
    function bindModeratorActions(){
        //edit
        var parent = $('#postmanage');
        $('.edit',parent).fancybox({href : '#blockeditcab', onClosed : function(){
                $(this.href).find('.thanks').hide().end()
                            .find('form').show();
        }});
        $('#blockeditcab form').ajaxForm({
            dataType: 'json',
            success: function(data){                    
                if(data.result == false){
                    $('#blockeditcab form p.message').text('message');
                }else{
                    $('#blockeditcab').find('form').hide().end().find('.thanks').show();
                }
            }
        });    
        
        
       //delete
       $('.delete',parent).fancybox({href : '#blockdeletecab'});
       $('#blockdeletecab form').ajaxForm({
            dataType: 'json',
            success: function(data){                    
                if(data.result == false){
                    $('#blockdeletecab form p.message').text('message');
                }else{
                    $('#blockdeletecab').find('form').hide().end().find('.thanks').show();
                }
            }
        });  
        
        //restore
       $('.restore',parent).fancybox({href : '#blockrestorecab'});
       $('#blockrestorecab form').ajaxForm({
            dataType: 'json',
            success: function(data){                    
                if(data.result == false){
                    $('#blockrestorecab form p.message').text('message');
                }else{
                    $('#blockrestorecab').find('form').hide().end().find('.thanks').show();
                }
            }
        });  
        
        //ban
        $('.banuser',parent).fancybox({href : '#blockbanuser'});
        
    }
   
    /**
     * Return absolute Y offset of an element
     * 
     * 
     */
    function getAbsoluteOffsetY(element)
    {
        var offset = 0;
        while( element != null ) {
            offset += element.offsetTop;
            element = element.offsetParent;
        }
        //console.log(offset);
        return offset;
    }
    
    function calculateOffset(){
        $('#cablist aside.info').each(function(index,element){
            $(this).data('offset',getAbsoluteOffsetY($(this).get(0)));
        });
        $('#cablist .cab').each(function(index,element){
            $(this).data('offset',getAbsoluteOffsetY($(this).get(0)));
        });
    }
    
    function getDocumentOffset(){
        return (document.documentElement.scrollTop + document.body.scrollTop
                == document.documentElement.scrollTop) ?
                document.documentElement.scrollTop : document.body.scrollTop;
    }
    function elementInViewport(el) {
        var rect = el.getBoundingClientRect();

        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= window.innerHeight &&
            rect.right <= window.innerWidth 
            )
    }

    function bindFloatingVoteBox(){
        $(window).data('postleft', calculate_position_stickyvote());
        $(window).resize(function(){
            $(window).data('postleft', calculate_position_stickyvote());
        });
                
        var box_height = $('.cab .info').height();
        var limit_top = $('#cablist .cab').eq(0).offset().top;
        var sticky_height = $('#cablist .cab .info:eq(0)').height();
        $(window).scroll(function(){                   
            if(window.scrollY < limit_top){
                //reset all boxes
                $('#cablist .cab .info').css('position','inherit').css('top','').css('left','');
                return;
            }
            var position_left = $(window).data('postleft');
            
            var box = $('#cablist .cab:in-viewport').eq(0);
            var box_offset = box.offset().top;
            //console.log(getDocumentOffset());
            //console.log(getAbsoluteOffsetY(box.get(0)));
            
            //console.log(box.height());
            //console.log(window.scrollY + sticky_height );
            //console.log(box.offset().top + box.height());
            if((window.scrollY + sticky_height ) > (box.offset().top + box.height())){
                $('#cablist .cab .info').css('position','inherit').css('top','').css('left','');
                return;
            }
            
            $('.info',box).css('position','fixed').css('top','0').css('left',position_left + 'px');
            $('#cablist .cab').not(box).find('.info').css('position','inherit').css('top','').css('left','');
                        
        });
    }
    
    function calculate_position_stickyvote(){
        return ($(document).width()/2 - $('#container-body > .wrap').width()/2) + 510;
    }
    
    function bindJsActionFollow(){
        $('.js-action-follow,.js-action-unfollow').click(function(){            

            var btn = $(this);
            var url = '';
            if($(btn).hasClass('js-action-follow')){
                url = 'member/dofollow/' + $(this).attr('id');            
                $.getJSON(url, function (data){
                    $(btn).removeClass('js-action-follow').addClass('js-action-unfollow')
                    .removeClass('btn-highlight').addClass('btn')
                    .text('Đã theo đuôi');
                });
            }
            if($(btn).hasClass('js-action-unfollow')){
                url = 'member/unfollow/' + $(this).attr('id');
                $.getJSON(url, function (data){
                    $(btn).removeClass('js-action-unfollow').addClass('js-action-follow')
                    .removeClass('btn').addClass('btn-highlight')
                    .text('Theo đuôi');
                });
            }

        });        
    }
    
    
    function relative_time(delta) {
        
        if (delta < 60) {
            return 'vài giây trước';
        } else if(delta < 120) {
            return '1 phút trước';
        } else if(delta < (60*60)) {
            return (parseInt(delta / 60)).toString() + ' phút trước';
        } else if(delta < (120*60)) {
            return '1 giờ trước';
        } else if(delta < (24*60*60)) {
            return (parseInt(delta / 3600)).toString() + ' tiếng trước';
        } else if(delta < (48*60*60)) {
            return '1 ngày trước';
        } else {
            return (parseInt(delta / 86400)).toString() + ' ngày trước';
        }
    }
    
    
    function bindTwitter()    {

        $.ajax({
            url: "http://twitter.com/statuses/user_timeline/coaibiet.json",
            data: {
                count: 1
            },
            dataType: "jsonp",
            success: function(getData){
                var tweet = $('<div/>').html(getData[0].text).text();
                $('.block-devtem .entry .message').html("<strong>@coaibiet:</strong>&nbsp;"+tweet).linkify();                
                //var time = getData[0].created_at;
                var time = Date.parse(getData[0].created_at);
                var time_unix = time/1000;
                var current_time = Math.round(new Date().getTime()/1000);

                var final_time = current_time - time_unix;
                //final_time = final_time * 1000;
                //console.log(relative_time(final_time));
                $('.block-devtem .entry .datetime').text(relative_time(final_time));
            }
        });
    }
    
    function initialiseJGrowl(){
        $.jGrowl.defaults.position = 'bottom-left';
    }
		function JayzKeaneLinkinPark() {
		var current, cabs = $('section.cab'),max = cabs.length - 1;

		// anchor tag
		current = 0;
		cabs.each(function() {
			$(this).attr('id', 'cab-' + current);
			current++;
		});

		current = -1;
		$(document).keyup(function(e,v) {
			if (!$(e.target).is("input, textarea")) {
				switch (e.keyCode) {
					case 74: // J
					current = current + 1;

					if (current > max) {
						window.location = $('#jumper .gonext').attr('href');
						return;
					}

					window.location.hash = "cab-" + current;
					cabs.removeClass('current').eq(current).addClass('current');
					break;
					
					case 75: // K
					current = Math.max(current - 1, 0);
					window.location.hash = "cab-" + current;
					cabs.removeClass('current').eq(current).addClass('current');
					break;
					
					case 76: // L
					cabs.eq(current).find('.heart').trigger('click');
					break;
				}
			}
		});
	}

	
});